package cn.blunce.utils.XmlParse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class DOMParsePerson {

    public static List<Person> getPersons(InputStream in) throws Exception {
        List<Person> persons = new ArrayList<Person>();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(in);

        Element root = document.getDocumentElement();
        NodeList personNodes = root.getElementsByTagName("person");
        for (int i = 0; i < personNodes.getLength(); i++) {
            Element personElement = (Element) personNodes.item(i);
            Integer id = Integer.valueOf(personElement.getAttribute("id"));
            Person person = new Person();
            person.setId(id);
            NodeList childList = personElement.getChildNodes();
            for (int j = 0; j < childList.getLength(); j++) {
                if (childList.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    if ("name".equals(childList.item(j).getNodeName())) {
                        String name = childList.item(j).getFirstChild()
                                .getNodeValue();
                        person.setName(name);
                    }
                    if ("age".equals(childList.item(j).getNodeName())) {
                        String age = childList.item(j).getFirstChild()
                                .getNodeValue();
                        person.setAge(new Short(age));
                    }
                }
            }
            persons.add(person);
        }
        in.close();
        return persons;
    }
}
